<!--
 * @Description: 新人首单立减峰值数据
 * @Author: liyujie
 * @Date: 2021/05/24
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/05/24
-->
<template>
    <div class="wrapper">
        <div
            class="content-wrapper"
            ref="contentWrapper"
        >
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    峰值数据
                </div>
                <div class="add-btn">
                    <el-button
                        type="primary"
                        size="medium"
                        @click="showSettingDialog"
                    >
                        月度峰值设置
                    </el-button>
                </div>
            </div>
            <!--基础数据-->
            <div class="base-statistics">
                <div class="base-statistics-view">
                    <div class="base-statistics-item">
                        <div class="base-statistics-item__label">平台补贴总支出：</div>
                        <div class="base-statistics-item__value">¥{{ statistic_info.budget_cost }}</div>
                    </div>
                    <div class="base-statistics-item">
                        <div class="base-statistics-item__label">参与用户总数：</div>
                        <div class="base-statistics-item__value">{{ statistic_info.student_count }}人</div>
                    </div>
                    <div class="base-statistics-item">
                        <div class="base-statistics-item__label">人均优惠金额：</div>
                        <div class="base-statistics-item__value">¥{{ statistic_info.budget_cost_avg }}</div>
                    </div>
                </div>
            </div>
            <!--图表区-->
            <div class="charts-view">
                <div class="title-view">
                    <div class="title">
                        数据图表
                    </div>
                    <div class="filter">
                        <div
                            class="time"
                            v-if="filterData.type === 1"
                        >
                            统计截止时间：{{ filterData.end_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm:ss') }}
                        </div>
                        <div
                            class="time"
                            v-else
                        >
                            统计时间：{{ filterData.start_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm:ss') }} - {{ filterData.end_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm:ss') }}
                        </div>
                        <el-select
                            v-model="filterData.type"
                            size="medium"
                            style="width: 152px"
                            @change="handleDateChange"
                        >
                            <el-option
                                label="全部"
                                :value="1"
                            />
                            <el-option
                                label="近7天"
                                :value="7"
                            />
                            <el-option
                                label="近30天"
                                :value="30"
                            />
                            <el-option
                                label="自定义"
                                :value="99"
                            />
                        </el-select>
                        <el-date-picker
                            v-model="dateTimeRange"
                            v-if="filterData.type === 99"
                            type="datetimerange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :default-time="['00:00:00', '23:59:59']"
                            size="medium"
                            :clearable="false"
                            style="width: 360px;margin-left: 12px"
                            value-format="timestamp"
                        />
                    </div>
                </div>
                <div class="tabs-view">
                    <div class="tabs-left">
                        <div
                            class="tab-item"
                            v-for="item in tabs"
                            :key="item.id"
                            :class="currentTab === item.id ? 'focus' : ''"
                            @click="handleTabChange(item.id)"
                        >
                            {{ item.label }}
                        </div>
                        <div
                            class="line"
                            :class="`line-${currentTab}`"
                        />
                    </div>
                    <div
                        class="tabs-right"
                        v-if="currentTab === 1"
                    >
                        <div
                            class="legend-item"
                            :class="isShowValue ? 'show' : 'hide'"
                            @click="handleLegendChange(1)"
                        >
                            <div class="legend-line"/>
                            <div class="legend-label">设置峰值</div>
                        </div>
                        <div
                            class="legend-item"
                            :class="isShowSubsidy ? 'show' : 'hide'"
                            @click="handleLegendChange(2)"
                        >
                            <div class="legend-line"/>
                            <div class="legend-label">平台补贴</div>
                        </div>
                    </div>
                </div>
                <div
                    class="echarts"
                    ref="echarts"
                    v-loading="tableLoading"
                    v-show="tableData.length"
                />
                <div
                    class="echarts empty"
                    v-loading="tableLoading"
                    v-show="!tableData.length"
                >
                    暂无数据
                </div>
            </div>
            <!--列表-->
            <div
                class="table-view"
                :style="{height: `${autoHeight}px`}"
            >
                <div class="title-view">
                    <div class="title">
                        数据明细
                    </div>
                </div>
                <el-table
                    :data="tableData"
                    height="calc(100% - 68px)"
                    style="width: 100%;margin-bottom: 60px"
                    ref="table"
                    class="data-table"
                    :cell-style="{height: '62px'}"
                    v-loading="tableLoading"
                >
                    <el-table-column
                        label="序号"
                        align="center"
                        width="80"
                        type="index"
                        fixed="left"
                    />
                    <el-table-column
                        label="日期"
                        align="center"
                    >
                        <template slot-scope="scope">
                            {{ scope.row.day_time * 1000 | dateFormatter('yyyy/MM/dd') }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="budget_today"
                        label="设置峰值（元）"
                        align="center"
                        :formatter="emptyFormatter"
                    />
                    <el-table-column
                        prop="budget_cost"
                        label="平台补贴支出（元）"
                        :render-header="(h, title, content) => renderHeader(h, '平台补贴支出（元）', '未提供文案')"
                        align="center"
                        :formatter="emptyFormatter"
                    />
                    <el-table-column
                        prop="student_count"
                        label="参与用户数"
                        align="center"
                    />
                    <el-table-column
                        prop="budget_cost_avg"
                        label="人均优惠金额（元）"
                        align="center"
                        :formatter="emptyFormatter"
                    />
                </el-table>
            </div>
            <!-- /分页 -->
            <div class="pagination-wrapper clearfix">
                <el-pagination
                    layout="total, prev, pager, next, jumper"
                    background
                    :current-page.sync="page.now_page"
                    :total="page.total_count"
                    :page-size="page.page_size"
                    @current-change="getTableData"
                />
            </div>
        </div>
        <!--峰值设置弹窗-->
        <peak-setting-dialog
            ref="settingDialog"
        />
    </div>
</template>

<script>
/**
 * 页面接收参数
 * @param no - 商品编号
 */

import {back} from '@/mixin/back';
import { deepClone } from "@/assets/js/utils";
import ECharts from "echarts";
import PeakSettingDialog from "./peak-setting-dialog";

export default {
    name: "FirstOrderDiscountStatistics",
    data() {
        return {
            filterData: {
                type: 1,
                start_time: 0,
                end_time: 0,
                result: 3
            },
            statistic_info: {
                budget_cost: 0,
                student_count: 0,
                budget_cost_avg: 0
            },
            dateTimeRange: [],
            tableData: [],
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 20
            },
            tableLoading: false,
            currentTab: 1,
            tabs: [
                {id: 1, label: '平台补贴&设置峰值'},
                {id: 2, label: '参与用户'},
                {id: 3, label: '人均优惠金额'}
            ],
            // 是否显示设置峰值
            isShowValue: true,
            // 是否显示平台补贴
            isShowSubsidy: true,
            chartConfigSubsidy: {
                tooltip: {
                    trigger: 'axis'
                },
                color:['#1890FF','#FFB218'],
                legend: {
                    data:['设置峰值','平台补贴'],
                    show: false
                },
                grid: {
                    top: '10%',
                    right: '2%',
                    bottom: '0%',
                    left: '2%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: [20, 20],
                    axisTick: {
                        show: false
                    },
                    axisLine:{
                        lineStyle:{
                            color:'#BBBBBB',
                        }
                    },
                    axisLabel : {
                        margin: 12,
                        textStyle: {
                            color: '#333333',
                            fontSize: 14,
                        }
                    },
                    data: []
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        lineStyle: {
                            type: "dashed",
                        }
                    },
                    axisLabel : {
                        margin: 12,
                        textStyle: {
                            color: '#333',
                            fontSize: 14,
                        }
                    },
                    axisTick: {
                        show: false
                    }
                },
                dataZoom: [
                    {
                        show: false,
                        start: 0,
                        end: 100,
                        bottom: 0
                    },
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                ],
                series: [
                    {
                        name: '设置峰值',
                        type: 'line',
                        data: []
                    },
                    {
                        name: '平台补贴',
                        type: 'line',
                        data: []
                    },
                ]
            },
            chartConfigUser: {
                tooltip: {
                    trigger: 'axis'
                },
                color:['#FFB218'],
                legend: {
                    data:['参与用户'],
                    show: false
                },
                grid: {
                    top: '10%',
                    right: '2%',
                    bottom: '0%',
                    left: '2%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: [20, 20],
                    axisTick: {
                        show: false
                    },
                    axisLine:{
                        lineStyle:{
                            color:'#BBBBBB',
                        }
                    },
                    axisLabel : {
                        margin: 12,
                        textStyle: {
                            color: '#333333',
                            fontSize: 14,
                        }
                    },
                    data: []
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        lineStyle: {
                            type: "dashed",
                        }
                    },
                    axisLabel : {
                        margin: 12,
                        textStyle: {
                            color: '#333',
                            fontSize: 14,
                        }
                    },
                    axisTick: {
                        show: false
                    }
                },
                dataZoom: [
                    {
                        show: false,
                        start: 0,
                        end: 100,
                        bottom: 0
                    },
                    {
                        type: 'inside',
                        start: 94,
                        end: 100
                    },
                ],
                series: [{
                    name: '参与用户',
                    data: [],
                    type: 'line'
                }]
            },
            chartConfigMoney: {
                tooltip: {
                    trigger: 'axis'
                },
                color:['#1890FF'],
                legend: {
                    data:['人均优惠金额'],
                    show: false
                },
                grid: {
                    top: '10%',
                    right: '2%',
                    bottom: '0%',
                    left: '2%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: ['20%', '20%'],
                    axisTick: {
                        show: false
                    },
                    axisLine:{
                        lineStyle:{
                            color:'#BBBBBB',
                        }
                    },
                    axisLabel : {
                        margin: 12,
                        textStyle: {
                            color: '#333333',
                            fontSize: 14,
                        }
                    },
                    data: []
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        lineStyle: {
                            type: "dashed",
                        }
                    },
                    axisLabel : {
                        margin: 12,
                        textStyle: {
                            color: '#333',
                            fontSize: 14,
                        }
                    },
                    axisTick: {
                        show: false
                    }
                },
                dataZoom: [
                    {
                        show: false,
                        start: 0,
                        end: 100,
                        bottom: 0
                    },
                    {
                        type: 'inside',
                        start: 94,
                        end: 100
                    },
                ],
                series: [{
                    name: '人均优惠金额',
                    data: [],
                    type: 'bar',
                    barMinWidth: 10,
                    barMaxWidth: 30,
                }]
            },
            // 图表
            chart: {},
            screenWidth: document.body.clientWidth,
            autoHeight: 1000,
            authResult: {}
        };
    },
    mixins: [back],
    components: {PeakSettingDialog},
    watch: {
        dateTimeRange(value) {
            this.filterData.start_time = value ? value[0] / 1000 : '';
            this.filterData.end_time = value ? value[1] / 1000 : '';
            this.getTableData(1);
        },
        screenWidth (val) {
            if (!this.timer) {
                this.screenWidth = val;
                this.timer = true;

                setTimeout( () => {
                    this.chart.resize();
                    this.calcAutoHeight();
                    this.timer = false;
                }, 300);
            }
        }
    },
    mounted() {
        this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'},{title: '新客首单立减'}, {title: '峰值数据'}]);
        this.chartConfigSubsidy.legend.selected = {
            '设置峰值': this.isShowValue,
            '平台补贴': this.isShowSubsidy,
        };
        this.filterData.end_time = Number(this.$moment().subtract(1, 'days').endOf('day').format("X"));
        this.getTableData(1);
        this.calcAutoHeight();
        this.authResult = this.$route.meta.authResult;
        window.onresize = () => {
            return (() => {
                window.screenWidth = document.body.clientWidth;
                this.screenWidth = window.screenWidth;
            })();
        };
    },
    methods: {

        /**
         * 获取数据
         */
        getTableData(page) {
            let params = { ...this.filterData };

            params.day_statistic_page_id = page || this.page.now_page;
            if(params.type === 99 && (params.end_time - params.start_time) > 60 * 60 * 24 * 365) {
                this.$message.warning('筛选间隔时间需小于1年');
                return;
            }
            this.tableLoading = true;
            this.$post('/student/shop_new_user_discount%5Cget_statistic', params, res => {
                if (res.code === 1) {
                    let config = {};
                    let day_time_list = [];
                    let budget_today_list = [];
                    let budget_cost_list = [];
                    let student_count_list = [];
                    let budget_cost_avg_list = [];

                    res.data.day_statistic_list.forEach(item => {
                        day_time_list.push(this.$moment(item.day_time * 1000).format('MM/DD'));
                        budget_today_list.push(item.budget_today);
                        budget_cost_list.push(item.budget_cost);
                        student_count_list.push(item.student_count);
                        budget_cost_avg_list.push(item.budget_cost_avg);
                    });

                    // this.page = res.data.day_statistic_page;
                    this.statistic_info = res.data.statistic;
                    this.tableData = res.data.day_statistic_list;
                    // x轴时间
                    this.chartConfigSubsidy.xAxis.data = day_time_list.reverse();
                    this.chartConfigUser.xAxis.data = day_time_list.reverse();
                    this.chartConfigMoney.xAxis.data = day_time_list.reverse();
                    // 设置峰值&平台补贴
                    this.chartConfigSubsidy.series[0].data = budget_today_list.reverse();
                    this.chartConfigSubsidy.series[1].data = budget_cost_list.reverse();
                    // 参与用户统计
                    this.chartConfigUser.series[0].data = student_count_list.reverse();
                    // 人均优惠统计
                    this.chartConfigMoney.series[0].data = budget_cost_avg_list.reverse();
                    config = this.currentTab === 1 ? this.chartConfigSubsidy : this.currentTab === 2 ? this.chartConfigUser : this.chartConfigMoney;
                    this.$nextTick(() => {
                        this.initEcharts(config);
                    });
                } else {
                    this.$notify({
                        title: '提示',
                        message: res.msg,
                        type: 'warning'
                    });
                }
                this.tableLoading = false;
            });
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 切换tab
         * @param val
         */
        handleTabChange(val) {
            this.currentTab = val;
            this.chart.clear();
            if(val === 1) {
                this.initEcharts(this.chartConfigSubsidy);
            }
            if(val === 2) {
                this.initEcharts(this.chartConfigUser);
            }
            if(val === 3) {
                this.initEcharts(this.chartConfigMoney);
            }
        },

        /**
         * 初始化图标
         * @param config
         */
        initEcharts(config) {
            this.chart = ECharts.init(this.$refs.echarts);
            this.chart.setOption(config);
        },

        /**
         * 图例切换
         * @param type - 1设置峰值 2平台补贴
         */
        handleLegendChange(type) {
            if(type === 1) {
                this.isShowValue = !this.isShowValue;
            }
            if(type === 2) {
                this.isShowSubsidy = !this.isShowSubsidy;
            }
            this.chartConfigSubsidy.legend.selected = {
                '设置峰值': this.isShowValue,
                '平台补贴': this.isShowSubsidy,
            };
            this.initEcharts(this.chartConfigSubsidy);
        },

        /**
         * 自定义表格标题hover提示
         */
        renderHeader(h,title, content){
            return h('span', {}, [
                h('span', {style: 'color:#333; font-weight: 500'}, title),
                h('el-popover', { props: { placement: 'top-start', width: '200', trigger: 'hover', content: content }}, [
                    h('i', { slot: 'reference', class:'el-icon-question', style: 'color:#999'}, '')
                ])
            ]);
        },

        /**
         * 更改日期
         * @param val - 统计天数
         */
        handleDateChange(val) {
            if(val !== 99) {
                this.filterData.end_time = Number(this.$moment().subtract(1, 'days').endOf('day').format("X"));
                this.filterData.start_time = Number(this.$moment().subtract(val, 'days').startOf('day').format("X"));
            }
            if(val === 1) {
                this.filterData.start_time = 0;
            }
            if(val === 99) {
                this.filterData.end_time = Number(this.$moment().subtract(1, 'days').endOf('day').format("X"));
                this.filterData.start_time = Number(this.$moment().subtract(1, 'days').startOf('day').format("X"));
            }
            this.dateTimeRange = [this.filterData.start_time * 1000, this.filterData.end_time * 1000];
        },

        /**
         * 显示峰值设置弹窗
         */
        showSettingDialog() {
            if(!this.authResult.auth_setting) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            this.$refs.settingDialog.show();
        },

        /**
         * 动态计算高度
         */
        calcAutoHeight() {
            this.autoHeight = this.$refs.contentWrapper.offsetHeight - 54;
        }
    }
};
</script>

<style scoped lang="less">
.wrapper {
    width: 100%;
    .content-wrapper {
        height: calc(100% - 24px);
        flex-direction: column;
        position: relative;
        margin: 12px;
        box-sizing: border-box;
        overflow-y: auto;
        &::-webkit-scrollbar {
            width: 0;
            height: 0;
        }

        /*header*/
        .header {
            height: 68px;
            padding: 24px;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #fff;
            border-bottom: 1px solid #F0F2F5;

            .header-title {
                color: #333333;
                font-size: 20px;
                height: 20px;
                font-weight: 500;
                position: relative;
                margin: 24px 0 24px 12px;

                &::before {
                    content: '';
                    position: absolute;
                    left: -8px;
                    top: -1px;
                    width: 3px;
                    height: 20px;
                    background: #1890FF;
                }
            }
        }
        .title-view {
            height: 64px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .title {
                font-size: 16px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #333333;
            }
            .filter {
                display: flex;
                align-items: center;
                .time {
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #999999;
                    margin-right: 12px;
                }
            }

        }
        .base-statistics {
            height: 96px;
            background: #fff;
            padding: 0 32px;
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            &-view {
                height: 44px;
                width: 100%;
                background: #EEF8FF;
                padding: 0 20px;
                display: flex;
            }
            &-item {
                margin-right: 32px;
                display: flex;
                align-items: center;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                &__label {
                    color: #333333;
                }
                &__value {
                    color: #2FBDB3;
                }
            }
        }
        .charts-view {
            height: 434px;
            background: #fff;
            display: flex;
            flex-direction: column;
            padding: 0 32px 24px;
            margin-bottom: 12px;
            .tabs-view {
                height: 56px;
                display: flex;
                justify-content: space-between;
                border-bottom: 1px solid #EBEEF5;
                align-items: center;
                user-select: none;
                .tabs-left {
                    display: flex;
                    align-items: center;
                    height: 100%;
                    position: relative;
                    .tab-item {
                        display: flex;
                        align-items: center;
                        height: 100%;
                        margin-right: 32px;
                        cursor: pointer;
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #666666;
                        &.focus {
                            font-family: PingFangSC-Medium, PingFang SC;
                            font-weight: 500;
                            color: #1890FF;
                        }
                    }
                    .line {
                        height: 2px;
                        background: #1890FF;
                        position: absolute;
                        bottom: 0;
                        transition: all .2s;
                        &.line-1 {
                            width: 123px;
                            left: 0;
                        }
                        &.line-2 {
                            width: 56px;
                            left: 156px;
                        }
                        &.line-3 {
                            width: 84px;
                            left: 245px;
                        }
                    }
                }
                .tabs-right {
                    display: flex;
                    align-items: center;
                    height: 100%;
                    .legend-item {
                        margin-left: 32px;
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #333333;
                        display: flex;
                        align-items: center;
                        height: 100%;
                        cursor: pointer;
                        user-select: none;
                        transition: all .2s;
                        .legend-line {
                            width: 40px;
                            height: 2px;
                            margin-right: 6px;
                        }
                        &:first-child .legend-line{
                            background: #1890FF;
                        }
                        &:last-child .legend-line{
                            background: #FFB218;
                        }
                        &.hide {
                            color: #ccc;
                            .legend-line {
                                background: #ccc;
                            }
                        }
                    }
                }
            }
            .echarts {
                flex: 1;
                &.empty {
                    color: #909399;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
            }
        }
        .table-view {
            height: 1000px;
            padding: 0 32px;
            background: #fff;
        }
    }
    // 表格
    .data-table {
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        // 操作按钮
        .option-btn-group {
            .el-button {
                margin-left: 0;
                margin-right: 10px;
            }
        }
    }
    /deep/ .el-table {
        th {
            background: #f4f4f4!important;
            font-size: 14px!important;
            font-family: PingFangSC-Medium, PingFang SC;
            color: #333333!important;
            .cell {
                font-weight: 500!important;
            }
        }
    }
    /* 分页 */
    .pagination-wrapper {
        padding: 12px 24px;
        background: #fff;
        .el-pagination {
            float: right;
            padding: 0;
            background-color: transparent;
        }
    }
}
</style>

